package dao;

import entity.Car;
import entity.User;
import utils.BaseDAO;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CarDAOImpl extends BaseDAO implements CarDAO {
    public int updateCar(Car car) {
        int count=0;
        String sql = "update t_car set name='"+car.getName()+"',car_name='"+car.getCar_name()+"',cost='"+car.getCost()+"',date='"+car.getDate()+"' where id='"+car.getId()+"'";
        count = this.executeUpdate(sql);
        closeAll();
        return count;
    }

    public int deleteCarById(int id) {
        int i = 0;
        String sql = "delete from t_car where id="+id;
        i = this.executeUpdate(sql);
        closeAll();
        return i;
    }

    public User login(String name, String passwd) {
        User user =null;
        String sql = "select * from user where name='"+name+"'and passwd="+passwd;
        ResultSet rs = this.executeQuery(sql);
        try {
            while(rs.next()){
                user=new User();
                user.setId(rs.getInt("id"));
                user.setName(rs.getString("name"));
                user.setPasswd(rs.getString("passwd"));
            }
            closeAll();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return user;
    }

    public List<Car> selectAll() {
        List<Car> list = new ArrayList<Car>();
        String sql = "select * from t_car";
        ResultSet rs = this.executeQuery(sql);
        try {
            while(rs.next()){
                Car car=new Car();
                car.setId(rs.getInt("id"));
                car.setName(rs.getString("name"));
                car.setCar_name(rs.getString("car_name"));
                car.setCost(rs.getInt("cost"));
                car.setDate(rs.getString("date"));
                list.add(car);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        closeAll();
        return list;
    }

    public Car selectCarById(int id) {
        Car car=null;
        String sql = "select * from t_car where id="+id;
        ResultSet rs = this.executeQuery(sql);
        try {
            while(rs.next()){
                car=new Car();
                car.setId(rs.getInt("id"));
                car.setName(rs.getString("name"));
                car.setCar_name(rs.getString("car_name"));
                car.setCost(rs.getInt("cost"));
                car.setDate(rs.getString("date"));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        closeAll();
        return car;
    }
}
